package edu.intprog.egreeting;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import edu.intprog.sql.SessionManager;
import edu.intprog.egreeting.basic.EgreetingBaseServlet;
import edu.intprog.egreeting.beans.Messages;
import edu.intprog.egreeting.beans.UserDef;

/**
 * Servlet implementation class for Servlet: UpdetServlet
 *
 */
public class UpdetServlet extends EgreetingBaseServlet implements javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public UpdetServlet() {
		super();
	}   	

	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
		if( request.getSession().getAttribute("user")==null)
		{
			//simple security measure
			getServletContext().getRequestDispatcher("/StartServlet").forward(request, response);
			return;
		}
		if (request.getParameter("cancel")!=null)
		{
			//cancel was pressed
			getServletContext().getRequestDispatcher("/welcomeGreeting.jsp").forward(request, response);
			return;
		}
		
		//get the old password and email address form the request
		String oldPassword=request.getParameter("oldPassword");
		String eMail=request.getParameter("emailAddr");
		
		String validationResult=new String();
		UserDef editedUser=null;

		//verify that the user user has entered the old password correctly - so they are 
		//identified correctly
		Transaction tx = null;
		Session session = SessionManager.getCurrentSession();
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("from edu.intprog.egreeting.beans.UserDef where EMAIL_ADDR=:eMail and USER_PASSWORD=:oldPassword");
			query.setString("eMail", eMail).setString("oldPassword", oldPassword);
			@SuppressWarnings("unchecked")
			List<UserDef> result = (List<UserDef>) query.list();
			tx.commit();
			if(result.size()!=1)
			{
				//user password is incorrect
				editedUser= new UserDef();
				validationResult = validationResult + "Old password is incorrect. <br/>";
			}
			else
			{
				//user password is ok
				editedUser = result.get(0);
			}
		} catch (HibernateException e) {
			e.printStackTrace();
			if (tx != null && tx.isActive())
				tx.rollback();
			//sql error
			validationResult = validationResult + e.getMessage() + "<br />";
		}

		//fill the user details from the request
		editedUser.set_fName(request.getParameter("fName"));
		editedUser.set_lName(request.getParameter("lName"));
		editedUser.set_emailAddr(request.getParameter("emailAddr"));
		editedUser.set_phoneNumber(request.getParameter("phoneNumber"));

		//only update the password if the new password field is not empty
		String newPassword=request.getParameter("newPassword");
		String newPassword2=request.getParameter("newPassword2");
		if(newPassword.equals("") && newPassword2.equals(""))
		{
			newPassword = oldPassword;
			newPassword2 = oldPassword;
		}

		editedUser.set_userPassword(newPassword);
		editedUser.set_userPassword2(newPassword2);

		// validate the user fields that they were filled correctly
		validationResult =validationResult+ editedUser.validate();

		if (validationResult.length() > 0)
		{
			//some error was detected
			Messages msgDef = new Messages();
			msgDef.set_errorMessage(validationResult);
			request.setAttribute("msgs", msgDef);
			getServletContext().getRequestDispatcher("/userDetails.jsp").forward(request, response);
		}
		else
		{
			//no errors - the edited user definition will be added to the DB
			session = SessionManager.getCurrentSession();
			tx = session.beginTransaction();

			String message = new String();
			Messages msgDef = new Messages();
			String destinationPage = "/welcomeGreeting.jsp";

			try
			{
				session.update(editedUser);
				tx.commit();

				message = "Account was updated successfully.<br/>";
				
				//update the user definition in the session
				request.getSession().setAttribute("user", editedUser);
				msgDef.set_infoMessage(message);
			}
			catch (HibernateException e) {
				e.printStackTrace();
				if (tx != null && tx.isActive())
					tx.rollback();
				//sql error
				destinationPage = "/userDetails.jsp";
				msgDef.set_errorMessage(e.getMessage() + "<br />");
			}
			request.setAttribute("msgs", msgDef);
			getServletContext().getRequestDispatcher(destinationPage).forward(request, response);
		}
	}
}